package com.neoCalf.neoCommon.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.neoCalf.neoCommon.enums.ResultCode;
import com.neoCalf.neoCommon.exception.BusinessException;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;


/**
 * @author 小牛
 * @version 1.0
 * &#064;description  阿里云短信服务配置
 * &#064;date  2024/2/24 14:15
 */
@Slf4j
@NoArgsConstructor
public class AliYunSmsUtil {
    private static final String accessKeyId = "LTAI5tEd1jNUrtUYDZjy1Ur6";
    private static final String accessKeySecret = "Z9CizQAWk1Il4A0Uqm8Zt5JIke6AmQ";
    private static final String signName = "MBTi性格解读";
    private static final String templateCode = "SMS_478100186";
    private static final String endpoint = "dysmsapi.aliyuncs.com";
    private static final Client client;

    /*
      使用AK&SK初始化账号Client
     */
    static {
        log.info("accessKeyId:{}", accessKeyId);
        log.info("accessKeySecret:{}", accessKeySecret);
        log.info("signName:{}", signName);
        log.info("templateCode:{}", templateCode);
        log.info("endpoint:{}", endpoint);
        Config config = new Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(accessKeyId)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = endpoint;
        try {
            client = new Client(config);
        } catch (Exception e) {
            log.error("阿里云短信服务初始化失败", e);
            throw new BusinessException(ResultCode.BusinessError);
        }
    }

    public static void sendCode(String phone, String code) throws BusinessException {
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phone);
        sendSmsRequest.setSignName(signName);
        sendSmsRequest.setTemplateCode(templateCode);
        sendSmsRequest.setTemplateParam("{\"code\":\"" + code + "\"}");
        try {
            client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            log.error("阿里云短信发送失败", e);
            throw new BusinessException(ResultCode.Fail);
        }
    }
}